package br.com.sig.presentation;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortOrder;

import br.com.sig.business.model.entity.BaseEntity;
import br.com.sig.presentation.action.BaseListAction;

public class BaseDataModel<T extends BaseEntity> extends LazyDataModel<T> {

	private static final long serialVersionUID = 3410301128629171408L;
	
	private Integer rowCount = 0;
	
	private BaseListAction<T> list;
	
	public BaseDataModel(BaseListAction<T> list) {
		this.list = list;
	}
	
	@Override
	public T getRowData(String rowKey) {
		for (T entity : getWrappedData()) {
			if (entity.getId().equals(new Long(rowKey))) {
				return entity;
			}
		}
		return null;
	}
	
	@Override
	public Object getRowKey(T entity) {
		return entity.getId();
	}
		
	@Override
	@SuppressWarnings("unchecked")
	public List<T> getWrappedData() {
		if (super.getWrappedData() == null) {
			setWrappedData(new ArrayList<T>());
		}
		return (List<T>) super.getWrappedData();
	}
	
	@Override
	public int getRowCount() {
		if (this.rowCount == null) {
			this.rowCount = list.createResultCount();
		}
		return this.rowCount;
	}
	
	@Override
	public List<T> load(int first, int pageSize, String sortField,
			SortOrder sortOrder, Map<String, Object> filters) {
		
		setWrappedData(list.createPagedResultList(first, pageSize));
		
		return getWrappedData();
	}
	
	public void init() {
		reset();
		this.rowCount = 0;
	}
	
	public void reset() {
		setRowCount(0);
		this.rowCount = null;
		setWrappedData(null);
	}

}